import thin_render from "./thin_render.mjs";
import thin_ajax from "./thin_ajax.mjs";
import { clearafterqueue } from "./delay_render.mjs";
import { thin } from "../thin3.mjs";
import { nearest_data } from "./nearest.mjs";

export default function (container, template) {
  let element = document.createElement("ajax");
  container.appendChild(element);
  element.thin_template = template; //锚定模板，以备rerender。
  element.thin_query = template.query; // 锚定查询参数
  element.thin_render = function () {
    thin(element).empty();
    let loading;
    if (template.loading) {
      loading = document.createElement("loading");
      element.appendChild(loading);
      thin_render(loading, template.loading || "loading...");
    }

    // ajax.thin_query = template.query; // 锚定查询参数
    thin_ajax({
      url: template.ajax,
      // data: JSON.stringify(container.thin_query),
      data:
        typeof element.thin_query === "function"
          ? element.thin_query({
              container,
              template,
              data: nearest_data(container),
            })
          : element.thin_query,
      dataType: template.dataType || "json",
      contentType: template.contentType || "application/json",
      success: (data) => {
        if (template.debug) {
          console.log({ data });
        }
        if (template.loading) thin(loading).remove();
        element.thin_data = data;
        thin_render(element, template.success);
        clearafterqueue();
        // thin.clearafterqueue();
        // if (template.pager) render_pager(container, template.pager);
      },
      error: (error, statusText) => {
        // console.log({ error, statusText });
        if (template.loading) thin(loading).remove();
        if (template.error) {
          // template.error.data = error;
          // thin_render(element, template.error);
          thin(element).render(template.error, error);
        } else {
          let err_template = {
            error_msg: [
              { f1: "[[statusText]]", title: "statusText" },
              {
                fieldset: [
                  { f3: "[[code]]", title: "code" },
                  { f3: "[[errno]]", title: "errno" },
                  { f3: "[[index]]", title: "index" },
                  { f3: "[[sql]]", title: "sql" },
                  { f3: "[[sqlMessage]]", title: "sqlMessage" },
                  { f3: "[[sqlState]]", title: "sqlState" },
                ],

                title: "responseJSON",
                datapath: "responseJSON",
              },
              { fieldset: "[[responseText]]", title: "responseText" },
            ],
            data: error,
          };
          thin_render(element, err_template);
        }
        // thin.clearafterqueue();
      },
    });
  };
  element.thin_render();
}
